package handler

import (
	"encoding/json"
	"fmt"
	"github.com/gocolly/colly"
	"sbd_xksite/models"
	"sbd_xksite/utils"
)

type Result struct {
	Rows    []models.Xksite `json:"rows"`
	Total   int             `json:"total"`
	Page    string          `json:"page"`
	Records string          `json:"records"`
}

type Param map[string]string

func ReListPageSizeHandler() (pageSize int) {
	data := Param{
		"LicenceNoLike":            "",
		"ApplyCompanyNameLike":     "",
		"ProductionManageCrops":    "",
		"IssuingAuthorityRegionID": "",
		"PublishDateStart":         "",
		"PublishDateEnd":           "",
		"VarietyName":              "",
		"_search":                  "false",
		"nd":                       "",
		"rows":                     "20",
		"page":                     "1",
		"sidx":                     "",
		"sord":                     "",
	}
	c := colly.NewCollector(colly.UserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36"))

	c.OnRequest(func(r *colly.Request) {
		// r.Headers.Set("Cookie", "JSESSIONID=A87C2BE548AF94B7CC4B9FA8E40178D0; pageSize=20; pageNo=1")
		r.Headers.Set("Content-Type", " application/x-www-form-urlencoded")

	})
	c.OnResponse(func(r *colly.Response) {
		var f interface{}
		json.Unmarshal(r.Body, &f)
		pageSize = int(f.(map[string]interface{})["total"].(float64))
		// fmt.Println(f.(map[string]interface{})["rows"])
		// fmt.Println(pageSize)

	})
	c.Post("http://202.127.42.47:6010/XKSite/Home/GetLicenseList", data)

	return
}

func ReListHandler(pageSize int) (isXksites []models.Xksite, err error) {

	var Result Result

	url := fmt.Sprintf("http://202.127.42.47:6010/XKSite/Home/GetLicenseList?&rows=20&page=%d&sord=desc", pageSize)

	c := colly.NewCollector(colly.UserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36"))

	c.OnRequest(func(r *colly.Request) {
		r.Headers.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9")
		r.Headers.Set("Upgrade-Insecure-Requests", "1")
		r.Headers.Set("Connection", "keep-alive")
		// r.Headers.Set("Cookie", "JSESSIONID=A87C2BE548AF94B7CC4B9FA8E40178D0; pageSize=20; pageNo=1")
		// r.Headers.Set("Content-Type", " application/x-www-form-urlencoded")

	})
	c.OnResponse(func(r *colly.Response) {
		err := json.Unmarshal(r.Body, &Result)
		if err != nil {
			fmt.Println("json.Unmarshal err :", err)
		}
		// ids := utils.SnowId(len(Result.Rows))
		// fmt.Println(ids)
		node := &utils.SnowFlake{}
		_ = node.Init(1, 5)
		for _, v := range Result.Rows {
			id, _ := node.NextId()
			v.ID = id
			isXksites = append(isXksites, v)

		}

	})
	c.Visit(url)

	return
}
